﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Data;
using DataMongo;
using DataMongo.Entities;
using Google.GData.Contacts;


namespace BreakingHubAdmin
{
    public static class UtilityService
    {
        public static string GetImageUrlFromSite(string stringUrl)
        {
            string htmlCode = string.Empty;
            using (WebClient client = new WebClient())
            {
                htmlCode = client.DownloadString(stringUrl);
            }

            List<Uri> links = new List<Uri>();
            var NoImageUrl = "../../Images/NoImage.jpg";
            string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection matchesImgSrc = Regex.Matches(htmlCode, regexImgSrc,
                RegexOptions.IgnoreCase | RegexOptions.Singleline);
            try
            {
                if (matchesImgSrc.Count > 0)
                {
                    foreach (Match m in matchesImgSrc)
                    {
                        string href = m.Groups[1].Value;
                        var newhref = new Uri(href).ToString().ToLower();
                        if ((newhref.Contains("/media/") || newhref.Contains("/assets/img/") ||
                             newhref.Contains("/assets/images/") || newhref.Contains("/assets/") ||
                             newhref.Contains("/images/article/") ||
                             newhref.Contains("/images/") || newhref.Contains("/files/"))
                             && !newhref.Contains("/ads/") && (!newhref.Contains(".png") && (newhref.Contains(".jpg") || newhref.Contains(".jpeg")) && (!newhref.Contains(".gif"))
                             && (newhref.Contains("height")) && (newhref.Contains("width"))
                             ))
                        {
                            return newhref;
                        }
                    }
                }
                return null;
            }

            catch (Exception e)
            {
                return null;
            }

        }

        public static string GetFacebookShareLink(int feedpostId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.FeedPostId == feedpostId
                                   select f).ToList();

            FeedPost feedpost = new FeedPost();
            if (list.Count > 0) feedpost = list[0];

            var postUrl = ConfigurationManager.AppSettings["ShareLinkUrl"].ToString() + "/Feed/" + feedpost.FeedPostId + "/" + feedpost.Title.Replace("'", "`");
            var fbsharelink = "javascript:popup_share('http://www.facebook.com/sharer.php?u=" + postUrl + "&t=Share',800,320)";
            return fbsharelink;

        }

        public static string GettwitterShareLink(int feedpostId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.FeedPostId == feedpostId
                                   select f).ToList();

            FeedPost feedpost = new FeedPost();
            if (list.Count > 0) feedpost = list[0];

            var postUrl = ConfigurationManager.AppSettings["ShareLinkUrl"].ToString() + "/Feed/" + feedpost.FeedPostId + "/" + feedpost.Title.Replace("'", "`");
            var twittersharelink = "javascript:popup_share('http://twitter.com/home?status=" + postUrl + "',800,320)";
            return twittersharelink;

        }

        public static string GetSourceNameById(int id)
        {
            var connection = new RepositoryBaseMongo("Source");
            List<Source> list = (from f in connection.GetAll<Source>()
                                 where f.SourceId == id
                                 select f).ToList();
            Source sources = new Source();
            if (list.Count > 0) sources = list[0];
            return sources.ShortDescription;
        }


        public static string GetCategoryNameById(int id)
        {
            var connection = new RepositoryBaseMongo("Category");
            List<Category> list = (from f in connection.GetAll<Category>()
                                 where f.CategoryId == id
                                 select f).ToList();
            Category category = new Category();
            if (list.Count > 0) category = list[0];
            return category.ShortDescription;
        }

        public static string RemoveSpecialCharacters(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if (((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') && c != 46)
                    sb.Append(c);

                if (c == 32 || c == 46)
                    sb.Append('-');

            }
            return sb.ToString();
        }

        public static int GetSourceFeedCount(int sourceId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.SourceId == sourceId
                                   select f).ToList();

            return list.Count();
        }

        public static int GeTagFeedsCount(int categoryId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.CategoryId == categoryId
                                   select f).ToList();

            return list.Count();

        }

        public static string GetTagbyCategory(int categoryId)
        {
            var connection = new RepositoryBaseMongo("Category");
            List<Category> list = (from f in connection.GetAll<Category>()
                                   where f.CategoryId == categoryId
                                   select f).ToList();
            Category category = new Category();
            if (list.Count > 0) category = list[0];
            return category.Tag;
        }


        public static bool DownloadImageFromUrl(string imageUrl, string saveurl)
        
        {
            try
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(imageUrl, saveurl);
                Thread.Sleep(1000);
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }


    }
}
